package cn.com.colasoft.dataStructure.list;

/**
 * 自己模拟实现LinkedList
 * @author lizhitao
 * @date 2018/12/11
 */
public class LinkedList<T> {

    private Integer length = 0;
    private ListNode<T> head;
    private ListNode<T> tail;


    public Integer length() {
        return length;
    }

    public ListNode<T> get(Integer index) {
        // copy head reference
        ListNode<T> newHead = head;
        while (index > 0 && newHead != null) {
            newHead = newHead.next;
            index --;
        }

        return newHead;
    }

    public void appendHead(T value) {
        ListNode<T> newHead = new ListNode<>(value);
        newHead.next = head;
        head = newHead;
    }

    public void appendTail(T value) {
        ListNode<T> tailNode = new ListNode<>(value);
        if (head == null) {
            head = tailNode;
            tail = head;
        } else {
            tail.next = tailNode;
        }

    }

    private class ListNode<T> {

        private T value;

        private ListNode<T> next;

        //private ListNode pre;

        public ListNode(T value) {
            this.value = value;
            this.next = null;
        }
    }

}
